<template>
  <div>
    <BreakSpace label="基本信息" :containerStyle="{ marginBottom: '10px' }"/>
    <FormPanel
      ref="baseInfo"
      :list="initFormBase"
      :cols="3"
      :labelWidth="170"
      :isSubmitBtn="false"
      :formType="handleType"
    />
    <div class="dialogBottmView">
      <el-button @click="closeDialogTop()">返 回</el-button>
      <el-button v-if="handleType != 'show'" @click="saveDialog()" :loading="saveLoading" type="primary">
        保存
      </el-button>
      <el-button v-if="pageType == 'DLR1' && handleType !== 'show'" @click="saveDialog('T')" :loading="saveLoading"
                 type="primary">
        保存并提交
      </el-button>
    </div>
  </div>
</template>
<script>
import {dictionary} from '@/utils/dictMixin';
import { region } from '@/api/cms-common/region';
import {formatdate} from '@/utils/index';
import {
  getDealerMatterFeedbackById,
  postSaveDealerMatterFeedback,
  postUpdateStatusByIds,
  putDealerMatterFeedback
} from '@/api/oa/dealerMatterFeedback';
import {getDealerCompanyByCode} from '@/api/part/exchange/platform';

export default {
  components: {},
  props: {
    handleType: {
      type: String,
      default: 'add'
    },
    pageType: {
      type: String,
      default: ''
    },
    value: {
      type: Object,
      default: null
    }
  },
  mixins: [dictionary,region],
  data() {
    return {
      downloadUrl: '/api/wmsIgnore/oa/dealerMatterFeedback/downloadFile',
      formData: {
        matterCategory: [],
        files: [],
      },
      initFormBase: this.initFormBaseFun(),
      visbleVehicle: false,
      saveLoading: false,
    };
  },
  mounted() {
    //判断是新增，还是修改
    if (this.handleType == 'add') {
      getDealerCompanyByCode().then(res => {
        console.info(res, '经销商信息----')
        const dealerInfo = res.data
        this.formData.dealerCode = dealerInfo.dealerCode
        this.formData.dealerName = dealerInfo.dealerName
        this.formData.businessDivision = dealerInfo.deptName
        this.formData.office = dealerInfo.officeName
        this.formData.dealerModality = dealerInfo.dealerFormName
        this.formData.province = dealerInfo.provinceId
        this.formData.city = dealerInfo.cityId
        this.init()
      })
    } else {
      getDealerMatterFeedbackById(this.value.id).then(res => {
        if (res.resultCode === 200) {
          const formData = res.data;
          console.info('obj', res.data)
          if (formData.matterCategory) {
            formData.matterCategory = formData.matterCategory.split(",");
          } else {
            formData.matterCategory = [];
          }
          if (formData.files) {
            formData.files = formData.files.map(i => {
              return {
                status: 'success',
                name: i.xtwjmc,
                url: i.xtwjlj,
              };
            });
          } else {
            formData.files = [];
          }
          if (formData.feedbackFiles) {
            formData.feedbackFiles = formData.feedbackFiles.map(i => {
              return {
                status: 'success',
                name: i.xtwjmc,
                url: `${this.downloadUrl}?fileId=${i.xtwjlj}&fileName=${i.xtwjmc}`,
              };
            });
          } else {
            formData.feedbackFiles = [];
          }
          this.formData = formData;
          this.init();
          this.initProvince();
        }
      })
    }
  },
  computed: {
    culFormData() {
      const formData = this.formData;
      if (formData.matterCategory) {
        formData.matterCategory = this.formData.matterCategory.join(',');
      }
      if (formData.files) {
        formData.files = this.formData.files.map(i => {
          return {
            xtfjlx: '8',
            xtwjmc: i.name,
            xtwjlj: i.url,
          };
        });
      }
      return formData;
    }
  },
  methods: {
    //修改时，初始化页面数据
    init() {
      //循环为表单赋值
      this.initFormBase.forEach(x => {
        if (this.formData[x.fieldName]) {
          x.initialValue = this.formData[x.fieldName];
        }
        //初始化所在市，区
        if(this.formData['province']){
          this.initCity(this.formData['province'],false);
        }
        if(this.formData['city']){
          this.initTown(this.formData['city'],false);
        }
      });
    },
    //初始化所在省份
    async initProvince(){
      let pl = this.createRegionList();
      this.initFormBase.find(item => item.fieldName === 'province').itemList = pl;
    },
    //初始化所在市数据
    async initCity(provinceId,flag = true){
      if(flag){
        //清空市
        this.initFormBase.find(item => item.fieldName === 'city').initialValue="";
        this.initFormBase.find(item => item.fieldName === 'city').itemList = [];
      }
      if(!provinceId || provinceId==null || typeof(provinceId)=='undefined'){
        return;
      }
      //取省数据
      let rd = this.getRegionData();
      this.cityData = rd[provinceId].children;
      let cl = this.createSubRegionList(this.cityData);
      this.initFormBase.find(item => item.fieldName === 'city').itemList = cl;
    },
    //初始化所在县数据
    async initTown(cityId){
      if(!cityId || cityId==null || typeof(cityId)=='undefined'){
        return;
      }
    },
    //基本表单信息
    initFormBaseFun() {
      return [
        {
          type: 'INPUT',
          label: '事项反馈单号',
          fieldName: 'matterFeedbackNum',
          placeholder: '请输入',
          hidden: this.handleType === 'add',
          initialValue: '',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'dealerCode',
          placeholder: '请输入',
          initialValue: '',
          readonly: true,
          disabled: true,
          rules: [
            {required: this.handleType != 'show', trigger: 'change', message: '请输入'}
          ],
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          placeholder: '请输入',
          initialValue: '',
          readonly: true,
          disabled: true,
          rules: [
            {required: this.handleType != 'show', trigger: 'change', message: '请输入'}
          ],
        },
        {//10
          type: 'SELECT',
          label: '省份',
          fieldName: 'province',
          placeholder: '请选择',
          initialValue: "",
          itemList:  [],
          hidden: this.pageType != 'OEM1',
          change: (value) => {
            this.initCity(value)
          },
          rules: [{
            required: true,
            message: '必填',
            trigger: 'change'
          }]
        },
        {//11
          type: 'SELECT',
          label: '城市',
          fieldName: 'city',
          placeholder: '请选择',
          itemList: [],
          hidden: this.pageType != 'OEM1',
          initialValue: "",
          change: (value) => {
            this.initTown(value)
          },
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'change'
            }
          ]
        },
        {
          type: 'INPUT',
          label: '事业部',
          fieldName: 'businessDivision',
          placeholder: '请输入',
          initialValue: '',
          // readonly: true,
          // disabled: true,
          hidden: this.pageType != 'OEM1',
          rules: [
            {required: false, trigger: 'change', message: '请输入'}
          ],
        },
        {
          type: 'INPUT',
          label: '办事处',
          fieldName: 'office',
          placeholder: '请输入',
          initialValue: '',
          // readonly: true,
          // disabled: true,
          hidden: this.pageType != 'OEM1',
          rules: [
            {required: false, trigger: 'change', message: '请输入'}
          ],
        },
        {
          type: 'INPUT',
          label: '经销商形式',
          fieldName: 'dealerModality',
          placeholder: '请输入',
          initialValue: '',
          // readonly: true,
          // disabled: true,
          hidden: this.pageType != 'OEM1',
          rules: [
            {required: this.handleType != 'show', trigger: 'change', message: '请输入'}
          ],
        },
        {
          type: 'INPUT',
          label: '联系人',
          fieldName: 'linkman',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            {required: this.handleType != 'show', trigger: 'change', message: '请输入'}
          ],
        },
        {
          type: 'INPUT',
          label: '联系人电话',
          fieldName: 'linkmanPhone',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            {required: this.handleType != 'show', trigger: 'change', message: '请输入'},
            {
              pattern: /^(([1][3,4,5,7,8][0-9]{9})|([0][1-9]{1}[0-9]{1,2}-[0-9]{5,10}))$/,
              message: '格式不正确',
              trigger: 'blur'
            }
          ],
        },
        {
          type: 'MULTIPLE_SELECT',
          label: '事项类别',
          fieldName: 'matterCategory',
          placeholder: '请选择',
          initialValue: [],
          itemList: this.createDictList('5020').map(i => {
            return {
              text: i.text,
              value: i.value + ''
            }
          }),
          selfCols: 3,
          rules: [
            {required: this.handleType != 'show', message: '请选择', trigger: 'change'},
          ]
        },
        {
          type: 'BREAK_SPACE',
          label: '事项反馈内容',
        },
        {
          type: 'TEXT_AREA',
          label: '事项描述',
          fieldName: 'matterDescription',
          initialValue: '',
          selfCols: 3,
          rules: [
            {required: this.handleType != 'show', trigger: 'blur', message: '请输入'},
          ]
        },
        {
          type: 'TEXT_AREA',
          label: '期望解决的内容和方式',
          fieldName: 'expectedSolution',
          initialValue: '',
          selfCols: 3,
          rules: [
            {required: this.handleType != 'show', trigger: 'blur', message: '请输入'},
          ]
        },
        {
          type: 'DATE_TIME',
          label: '期望完成时间',
          fieldName: 'expectedSolutionTime',
          placeholder: '请选择',
          initialValue: '',
          format: 'yyyy-MM-dd HH:mm:ss',
          minDateTime: formatdate(new Date(), 1),
          rules: [
            {required: this.handleType != 'show', trigger: 'change', message: '请选择期望完成时间'},
          ],
        },
        {
          type: 'UPLOAD_FILE',
          label: '附件',
          fieldName: 'files',
          upload: {
            actionUrl: '/api/file/oss/upload', //上传的地址
            // fileTypes: ['jpg', 'png', 'pdf', 'rar'],
            max: 1024 * 100,
            limit: 10
          },
          initialValue: [],
          disabled: false,
          selfCols: 3
        },
        {
          type: 'BREAK_SPACE',
          label: '事项回复内容',
          hidden: this.handleType != 'show',
        },
        {
          type: 'TEXT_AREA',
          label: '事项反馈回复',
          fieldName: 'feedbackReply',
          readonly: true,
          selfCols: 3,
          initialValue: '',
          hidden: this.handleType != 'show',
        },
        {
          type: 'INPUT',
          label: '回复人员',
          fieldName: 'feedbackReplyPeople',
          readonly: true,
          initialValue: '',
          hidden: this.handleType != 'show',
        },
        {
          type: 'DATE_TIME',
          label: '回复时间',
          fieldName: 'feedbackReplyTime',
          placeholder: ' ',
          initialValue: '',
          format: 'yyyy-MM-dd HH:mm:ss',
          hidden: this.handleType != 'show',
        },
        {
          type: 'UPLOAD_FILE',
          label: '回复附件',
          fieldName: 'feedbackFiles',
          upload: {
            actionUrl: '/api/file/oss/upload', //上传的地址
            // fileTypes: ['jpg', 'png', 'pdf', 'rar'],
            max: 1024 * 100,
            limit: 10
          },
          hidden: this.handleType != 'show',
          initialValue: [],
          disabled: false,
          selfCols: 3
        },
      ];
    },
    //保存
    async saveDialog(status = 'S') {
      this.saveLoading = true;
      let [err, data] = await this.$refs.baseInfo.GET_FORM_DATA();
      if (err) {
      } else {
        this.formData = Object.assign({}, this.formData, data);
        const formData = {
          ...this.culFormData,
          status
        }
        console.info(formData, 'formData----')
        let res;
        if (this.handleType === "add") { // 新增
          res = await postSaveDealerMatterFeedback(formData);
        } else { // 修改
          res = await putDealerMatterFeedback(formData);
        }
        if (res.resultCode === 200) {
          this.$notify.success({title: '提示信息', message: status == 'T' ? '提交成功' : '保存成功!'});
          // 重新加载
          this.closeDialog('refresh');
        }
      }
      this.saveLoading = false;
    },
    // 提报
    async tbHandle(status) {
      this.saveLoading = true
      const res = await postUpdateStatusByIds({
        status,
        ids: [this.formData.id]
      })
      if (res.resultCode == 200) {
        this.$notify.success({title: '提示信息', message: '提报成功'});
        this.closeDialog('refresh');
      }
      this.saveLoading = false
    },
    closeDialogTop(confirm) {
      if (confirm) {
        this.$confirm('确认关闭窗口吗？您所做的操作将不会被保存！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.closeDialog('closeDialog');
        })
      } else {
        this.closeDialog('closeDialog');
      }
    },
    //取消操作
    closeDialog(type) {
      this.$emit('close', type);
    }
  }
};
</script>

<style lang="less" scoped>
</style>
